package com.jdy.haoduoaiteacher.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.jdy.haoduoaiteacher.adapter.NormalQuestionListAdapter;
import com.jdy.haoduoaiteacher.model.NormalQuestion;
import com.jdy.haoduoaiteacher.model.NormalQuestionObject;
import com.jdy.haoduoaiteacher.parse.JsonSerializer;
import com.jdy.haoduoaiteacher.scan.decode.RGBLuminanceSource;
import com.jdy.haoduoaiteacher.util.FileManager;
import com.jdy.haoduoaiteacher.util.Tools;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

//import com.jdy.haoduoaiteacher.R;

@SuppressLint("NewApi")
public class SettingCustomServiceActivity extends BaseActivity {

  @InjectView(id = R.id.list_hardware)
  private ListView list_hardware;
  @InjectView(id = R.id.tv_phonenum)
  private TextView tv_phonenum;

  private ImageView img_xxbyuer, img_xxbfuwu;

  // @InjectView(id = R.id.list_app)
  // private ListView list_app;
  // @InjectView(id = R.id.list_netproblem)
  // private ListView list_netproblem;
  // @InjectView(id = R.id.list_maintain)
  // private ListView list_maintain;

  private NormalQuestionListAdapter mHardWareListAdapter;
  // private NormalQuestionListAdapter mAppListAdapter;
  // private NormalQuestionListAdapter mNetProblemListAdapter;
  // private NormalQuestionListAdapter mMainTainListAdapter;

  private NormalQuestionObject mNormalQuestionObject;

  private String tel = "400-517-517";

  private String time;
  private File file = null;

  private void saveCurrentImage() {
    // 获取当前屏幕的大小
    int width = getWindow().getDecorView().getRootView().getWidth();
    int height = getWindow().getDecorView().getRootView().getHeight();
    // 生成相同大小的图片
    Bitmap temBitmap = Bitmap.createBitmap(width, height,
        Bitmap.Config.ARGB_8888);
    // 找到当前页面的根布局
    // View view = getWindow().getDecorView().getRootView();
    // 设置缓存
    // view.setDrawingCacheEnabled(true);
    // view.buildDrawingCache();

    img_xxbyuer.setDrawingCacheEnabled(true);
    img_xxbyuer.buildDrawingCache();
    // 从缓存中获取当前屏幕的图片,创建一个DrawingCache的拷贝，因为DrawingCache得到的位图在禁用后会被回收
    temBitmap = img_xxbyuer.getDrawingCache();
    SimpleDateFormat df = new SimpleDateFormat("yyyymmddhhmmss");
    time = df.format(new Date());
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
      file = new File(Environment.getExternalStorageDirectory()
          .getAbsolutePath() + "/screen", time + ".png");
      if (!file.exists()) {
        file.getParentFile().mkdirs();
        try {
          file.createNewFile();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      FileOutputStream fos = null;
      try {
        fos = new FileOutputStream(file);
        temBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      new Thread(new Runnable() {
        @Override
        public void run() {
          String path = Environment.getExternalStorageDirectory()
              .getAbsolutePath() + "/screen/" + time + ".png";
          final Result result = parseQRcodeBitmap(path);
          runOnUiThread(new Runnable() {
            @Override
            public void run() {

              Intent intent = new Intent();
              if (Tools.isEmpty(result.toString()))
                return;
              intent.putExtra("link", result.toString());
              intent.setClass(SettingCustomServiceActivity.this,
                  SliderActivity.class);
              startActivity(intent);
              // getActivity().overridePendingTransition(R.anim.push_left_in,
              // R.anim.push_left_out);

              Toast.makeText(SettingCustomServiceActivity.this,
                  result.toString(), Toast.LENGTH_LONG).show();
            }
          });
        }
      }).start();
      // 禁用DrawingCahce否则会影响性能 ,而且不禁止会导致每次截图到保存的是缓存的位图
      img_xxbyuer.setDrawingCacheEnabled(false);
    }
  }

  // 解析二维码图片,返回结果封装在Result对象中
  private com.google.zxing.Result parseQRcodeBitmap(String bitmapPath) {
    // 解析转换类型UTF-8
    Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
    hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
    // 获取到待解析的图片
    BitmapFactory.Options options = new BitmapFactory.Options();
    // 如果我们把inJustDecodeBounds设为true，那么BitmapFactory.decodeFile(String path,
    // Options opt)
    // 并不会真的返回一个Bitmap给你，它仅仅会把它的宽，高取回来给你
    options.inJustDecodeBounds = true;
    // 此时的bitmap是null，这段代码之后，options.outWidth 和 options.outHeight就是我们想要的宽和高了
    Bitmap bitmap = BitmapFactory.decodeFile(bitmapPath, options);
    // 我们现在想取出来的图片的边长（二维码图片是正方形的）设置为400像素
    // 以上这种做法，虽然把bitmap限定到了我们要的大小，但是并没有节约内存，如果要节约内存，我们还需要使用inSimpleSize这个属性
    options.inSampleSize = options.outHeight / 400;
    if (options.inSampleSize <= 0) {
      options.inSampleSize = 1; // 防止其值小于或等于0
    }
    /**
     * 辅助节约内存设置
     * 
     * options.inPreferredConfig = Bitmap.Config.ARGB_4444; //
     * 默认是Bitmap.Config.ARGB_8888 options.inPurgeable = true;
     * options.inInputShareable = true;
     */
    options.inJustDecodeBounds = false;
    bitmap = BitmapFactory.decodeFile(bitmapPath, options);
    // 新建一个RGBLuminanceSource对象，将bitmap图片传给此对象
    RGBLuminanceSource rgbLuminanceSource = new RGBLuminanceSource(bitmap);
    // 将图片转换成二进制图片
    BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
        rgbLuminanceSource));
    // 初始化解析对象
    QRCodeReader reader = new QRCodeReader();
    // 开始解析
    Result result = null;
    try {
      result = reader.decode(binaryBitmap, hints);
    } catch (Exception e) {
      // TODO: handle exception
    }
    return result;
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.setting_customerservice_layout);
    setTitle("联系客服");

    setTitle_BgColor(0xff67c1ed);

    img_xxbyuer = (ImageView) findViewById(R.id.img_xxbyuer);
    img_xxbfuwu = (ImageView) findViewById(R.id.img_xxbfuwu);

    // img_xxbyuer.setOnLongClickListener(new OnLongClickListener() {
    //
    // @Override
    // public boolean onLongClick(View v) {
    // saveCurrentImage();
    // return true;
    // }
    // });

    tv_phonenum.setText("客服电话：" + tel);

    getbtn_right().setBackgroundResource(R.drawable.phoneservice_icon);
    getbtn_right().setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));
        startActivity(intent);
      }
    });

    String json = FileManager.ReadFromAssetfile("normalquestion.json");
    if (Tools.isNotEmpty(json)) {
      mNormalQuestionObject = JsonSerializer.getInstance().deserialize(json,
          NormalQuestionObject.class);
    }

    List<String> tempList = new ArrayList<String>();

    if (Tools.isNotEmpty(mNormalQuestionObject)
        && Tools.isNotEmpty(mNormalQuestionObject.normalquestion)) {
      for (NormalQuestion nq : mNormalQuestionObject.normalquestion) {
        tempList.add(nq.question);
      }
    }

    if (!tempList.isEmpty()) {
      mHardWareListAdapter = new NormalQuestionListAdapter(tempList, this);
      list_hardware.setAdapter(mHardWareListAdapter);
      Tools.setListViewHeightBasedOnChildren(list_hardware);
    }

    // if (!tempList.isEmpty()) {
    // mAppListAdapter = new NormalQuestionListAdapter(tempList, this);
    // list_app.setAdapter(mAppListAdapter);
    // }
    //
    // if (!tempList.isEmpty()) {
    // mNetProblemListAdapter = new NormalQuestionListAdapter(tempList, this);
    // list_netproblem.setAdapter(mNetProblemListAdapter);
    // }
    //
    // if (!tempList.isEmpty()) {
    // mMainTainListAdapter = new NormalQuestionListAdapter(tempList, this);
    // list_maintain.setAdapter(mMainTainListAdapter);
    // }
  }
}
